<script setup lang="ts">
import { nextTick, onMounted, reactive, ref } from 'vue'
import { queryAllCategories } from '@/api/category'
import type { CategoryVo } from '@/api/category/type'
import type { ElTree } from 'element-plus'

// 向父组件上抛的事件
const emit = defineEmits(['sendCategoryID', 'sendCategoryVos'])
// 分类集合
const categoryVos = ref<CategoryVo[]>()
// 页面加载后查询分类信息，以树形结构返回
onMounted(async () => {
  await queryAllCategories()
    .then((res) => {
      categoryVos.value = res
      emit('sendCategoryVos', categoryVos.value)
    })
    .catch((err) => console.log(err))
})
const defaultProps = {
  children: 'children',
  label: 'name',
}
// 树实例
const treeRef = ref<InstanceType<typeof ElTree>>()

// 分类id，用于传递给父组件
const categoryID = ref<number>(0)

// 点击节点时获取节点的分类id，并传递给父组件
const getCategoryID = (nodeObject, node) => {
  if (node.data.catLevel == 3) {
    categoryID.value = node.data.categoryID
    emit('sendCategoryID', categoryID.value)
  }
}
</script>

<template>
  <div class="container">
    <!--    以树形结构显示分类信息-->
    <el-tree
      :data="categoryVos"
      show-checkbox
      :props="defaultProps"
      :expand-on-click-node="false"
      node-key="categoryID"
      ref="treeRef"
      @node-click="getCategoryID"
    >
      <template #default="{ node, data }">
        <div class="custom-tree-node">
          <span>{{ node.label }}</span>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<style scoped>
.container {
  padding: 1rem;

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 1rem;
  }
}
</style>
